package com.jyy.prefabricated.service;

import com.baidubce.Protocol;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;

/**
 * @version 1.0.0
 * @author: zjj
 */

@Slf4j
@Service
public class BosService {


    @Value("${bos.accessKey}")
    private String accessKey; //用户的Access Key

    @Value("${bos.secretKey}")
    private String secretKey; //用户的Secret Key

    @Value("${bos.endpoint}")
    private String endpoint; //所属区域名

    @Value("${bos.bucketName}")
    private String bucketName; //所属区域名

    private BosClient client = null;

    /**
     * 上传文件
     */
    public String putObject(MultipartFile mfile, String objectKey)throws IOException{

        if (client == null) {
            synchronized(this) {
                client = getBosClient(accessKey, secretKey, endpoint);
            }
        }

        //转换格式MultipartFile转File
        File file = null;
        if(mfile.equals("")||mfile.getSize()<=0){
            mfile = null;
        }else{
            InputStream ins = mfile.getInputStream();
            file=new File(mfile.getOriginalFilename());
            inputStreamToFile(ins, file);
        }

        //上传文件
        client.putObject(bucketName, objectKey, file);

        //删除临时文件
        File del = new File(file.toURI());
        del.delete();

        String url = "http://oss.jianyeyun.cn/" + objectKey;
        return url;

        /*//返回url
        URL url = client.generatePresignedUrl(bucketName, objectKey, -1);

        String urlString = url.toString();
        int index;
        if ( (index = urlString.indexOf("?authorization")) != -1) {
            return urlString.substring(0, index);
        }
        return urlString;*/
    }


    /**
     * 上传文件
     */
    public String putFile(File file, String objectKey)throws IOException{

        if (client == null) {
            synchronized(this) {
                client = getBosClient(accessKey, secretKey, endpoint);
            }
        }

        //上传文件
        client.putObject(bucketName, objectKey, file);

        //删除临时文件
        File del = new File(file.toURI());
        del.delete();

        String url = "http://oss.jianyeyun.cn/" + objectKey;
        return url;

        /*//返回url
        URL url = client.generatePresignedUrl(bucketName, objectKey, -1);

        String urlString = url.toString();
        int index;
        if ( (index = urlString.indexOf("?authorization")) != -1) {
            return urlString.substring(0, index);
        }
        return urlString;*/
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectKey
     */
    public void deleteObject(String bucketName,String objectKey) {
        if (client == null) {
            synchronized(this) {
                client = getBosClient(accessKey, secretKey, endpoint);
            }
        }
        client.deleteObject(bucketName, objectKey);           //指定要删除的Object所在Bucket名称和该Object名称
    }


    public static void main(String[] args) {
        String url = "https://gz.bcebos.com/v1/img-kaoshi/73c3d89f55534267afe54d07347d9201.png";
        String name = url.substring(url.lastIndexOf('/') +1);
        System.out.println(name);
    }

    private BosClient getBosClient(String ACCESS_KEY_ID, String SECRET_ACCESS_KEY, String ENDPOINT) {
        //BosClient是BOS服务的客户端
        //初始化BosClient
        BosClientConfiguration config = new BosClientConfiguration();

        // 设置最大连接数为HTTP10
        config.setMaxConnections(10);
        // 设置连接超时为毫秒TCP5000
        config.setConnectionTimeoutInMillis(5000);
        // 设置传输数据超时的时间为毫秒Socket2000
        config.setSocketTimeoutInMillis(2000);

        //创建客户端bos
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        config.setEndpoint(ENDPOINT);		//指定所属区域
        config.setProtocol(Protocol.HTTPS);	//如果不指明，则使用http
        client = new BosClient(config);
        return client;
    }

    /**
     * 格式转换
     * @param ins
     * @param file
     */
    public void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public BosClient initCosClient(String ACCESS_KEY_ID, String SECRET_ACCESS_KEY) {
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        BosClient client = new BosClient(config);

        return client;
    }

    public Boolean bucketExit(BosClient bosClient, String bucketName) {
        boolean exists = bosClient.doesBucketExist(bucketName);
        return exists;
    }


    public String uploadFile(MultipartFile file) throws IOException {

        log.info("初始化BOS客户端");
        String ACCESS_KEY_ID = "1000189f5f0d4e2e94e16761a4a23e37";		//用户的Access Key
        String SECRET_ACCESS_KEY = "699526703dc344d5823e1a6a65fa6aa3";
        String bucketName = "";
        BosClient client = initCosClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        InputStream inputStream = file.getInputStream();
        String objectKey = file.getOriginalFilename();
        try {
            client.putObject(bucketName, objectKey, inputStream);
            return "success";
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return "false";
        }
    }
}
